package com.erp.erp_mask.controller;

import com.erp.erp_mask.pojo.TRoles;
import com.erp.erp_mask.service.TPermissionsService;
import com.erp.erp_mask.service.TRolePermissionsService;
import com.erp.erp_mask.service.TRolesService;
import com.erp.erp_mask.vo.Result;
import com.erp.erp_mask.vo.TreeData;
import jakarta.annotation.Resource;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @BelongsProject: erp
 * @BelongsPackage: com.erp.erp_mask.controller
 * @Author: wang
 * @CreateTime: 2024-05-09  21:05
 * @Description: TODO
 * @Version: 1.0
 * @effect:
 */
@RestController
@RequestMapping("/role")
public class TRolesController {
    @Resource
    private TRolesService tRolesService;
    @Resource
    private TPermissionsService tPermissionsService;
    @Resource
    private TRolePermissionsService tRolePermissionsService;

    @GetMapping("/index")
    public ModelAndView index() {
        return new ModelAndView("/sys/role");
    }

    @GetMapping("/search")
    public Result searchrole(@RequestParam("name") String name,@RequestParam("state") Integer state,Long pageNo,Long pageSize) {
        return Result.success(tRolesService.searchRoles(name, state,pageNo,pageSize));
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody TRoles role){
        try{
            tRolesService.save(role);
            return Result.success("新增角色成功");
        }catch (Exception e){
            return Result.fail("新增角色失败");
        }
    }

    @PutMapping("/update")
    public Result update(@RequestBody TRoles role){
        try {
            tRolesService.updateById(role);
            return Result.success("角色修改成功！");
        }catch (Exception e){
            return Result.fail("角色修改失败!");
        }
    }


    @DeleteMapping("/del")
    public Result del(Integer roleId){
        try{
            tRolesService.removeById(roleId);
            return Result.success("角色删除成功！");
        }catch (Exception ex){
            return Result.fail("角色删除失败！");
        }
    }
    @GetMapping("/getTreeData")
    public Result getTreeData(Long roleId){
        TreeData treeData = tPermissionsService.findTreeData(roleId);
        return Result.success(treeData);
    }
    @GetMapping("/grant")
   public Result grant(Long roleId, Long[] ids){
        try{
            tRolePermissionsService.grant(roleId,ids);
            return Result.success("角色授权成功！");
        }catch (Exception ex){
            return Result.fail("角色授权失败！");
        }
    }

}
